package com.mgface.framework.ws.service;

import java.io.IOException;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

@ServerEndpoint("/echo")
public class EchoAnnotation {
	private static final Logger log = LogManager.getLogger(EchoAnnotation.class);

	/**
	 * 打开websocket
	 */
	@OnOpen
	public void onOpen(Session session) {
		log.info(() -> "获得session:" + session.getId());
	}

	/**
	 * 关闭websocket
	 */
	public void onClose(Session session) {
		log.info(() -> "session退出:" + session.getId());
	}

	/**
	 * 处理接收消息
	 * 
	 * @param session
	 * @param msg
	 * @param last
	 */
	@OnMessage
	public void echoTextMessage(Session session, String msg, boolean last) {
		log.info(() -> "接收到消息:" + msg + ",标识:" + last);
		try {
			if (session.isOpen()) {
				/**
				 * sendText方法解释:发送部分文本消息,阻塞直到所有消息都已发送,运行时按顺序读取消息。
				 * 消息的非最终部分发送时,isLast设置为false.最后一部分发送必须把isLast设置为true。
				 */
				session.getBasicRemote().sendText("server->" + msg, last);
			}
		} catch (IOException e) {
			try {
				session.close();
			} catch (IOException e1) {
			}
		}
	}
}
